package com.pengcheng.taskapplication.mvp.view.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pengcheng.taskapplication.R;
import com.pengcheng.taskapplication.model.SortModel;
import com.pengcheng.taskapplication.mvp.view.widget.CodeView;
import com.pengcheng.taskapplication.mvp.view.widget.PwdCodeView;
import com.pengcheng.taskapplication.util.ToastUtils;

import java.math.BigDecimal;
import java.util.ArrayList;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link InputPwdDialogFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link InputPwdDialogFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class InputPwdDialogFragment extends DialogFragment implements View.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "model";
    private static final String ARG_PARAM2 = "arg2";
    // TODO: Rename and change types of parameters
    private TextView tv_pay_name,tv_money;

    private LinearLayout ll_select;

    private OnFragmentInteractionListener mListener;

    private SortModel model;

    private double money;

    public InputPwdDialogFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment IntegralDialogFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static InputPwdDialogFragment newInstance(SortModel sortModel,double money) {
        InputPwdDialogFragment fragment = new InputPwdDialogFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1,sortModel);
        args.putDouble(ARG_PARAM2,money);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            model = (SortModel)getArguments().getSerializable(ARG_PARAM1);
            money=(double)getArguments().getDouble(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().setCanceledOnTouchOutside(false);
        getDialog().getWindow().getAttributes().windowAnimations=R.style.BottomAnimation;
        View rootView=inflater.inflate(R.layout.fragment_input_pwd_dialog, container, false);
        PwdCodeView codeView=(PwdCodeView) rootView.findViewById(R.id.code_view);
        codeView.setmInputListener(new PwdCodeView.OnInputFinishListener() {
            @Override
            public void onFinish(String code) {
                onConfirm(code);
                dismiss();
            }
        });
        ll_select=(LinearLayout)rootView.findViewById(R.id.ll_select);
        tv_pay_name=(TextView)rootView.findViewById(R.id.tv_pay_name);
        tv_money=(TextView)rootView.findViewById(R.id.tv_money);
        ll_select.setOnClickListener(this);
        return rootView;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(model!=null){
            tv_pay_name.setText(model.getName());
            BigDecimal bg = new BigDecimal(money/100);
            tv_money.setText("￥"+bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onConfirm(String pwd) {
        if (mListener != null) {
            mListener.onConfirm(pwd);
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void checkPayType() {
        if (mListener != null) {
            mListener.checkPayType();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_select:
                checkPayType();
                dismiss();
                break;
        }

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onConfirm(String pwd);
        void checkPayType();

    }


    @Override
    public void show(FragmentManager manager, String tag) {
        //避免重复添加的异常 java.lang.IllegalStateException: Fragment already added
        Fragment fragment = manager.findFragmentByTag(tag);
        if (fragment != null) {
            FragmentTransaction fragmentTransaction = manager.beginTransaction();
            fragmentTransaction.remove(fragment);
            fragmentTransaction.commitAllowingStateLoss();
        }
        //避免状态丢失的异常 java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
        try {
            super.show(manager, tag);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

}
